package com.tqyan.model.controller.request;

import com.alibaba.fastjson.JSONObject;
import com.tqyan.model.exp.DefaultException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @description OpenAI聊天请求
 * <p>
 * {
 *   "model": "gpt-3.5-turbo",
 *   "messages": [{"role": "user", "content": "Hello!"}]
 * }
 * </p>
 *
 * @author 陈晨
 * @date 2023/4/10 16:55
 */
@Data
@Slf4j
public class OpenAIChatRequest implements Serializable {
    private static final long serialVersionUID = -4489762670856983555L;

    /** 模型 */
    private String model;
    /** 温度 */
    private Double temperature;
    /** 流响应, 类似ChatGPT */
    private Boolean stream;
    /** 请求内容 */
    private List<OpenAIChatMessageRequest> messages;

    /**
     * @description 添加请求内容
     * <p> <功能详细描述> </p>
     *
     * @author 陈晨
     * @date 2023/4/12 15:38
     */
    public OpenAIChatMessageRequest addMessage(String role, String content) {
        if (StringUtils.isBlank(content)) {
            throw new DefaultException("内容不可为空");
        }
        if (null == messages) {
            messages = new ArrayList<>();
        }
        OpenAIChatMessageRequest message = new OpenAIChatMessageRequest(role, content);
        messages.add(0, message);
        return message;
    }
    
    public void leftPad(String content) {
        if (CollectionUtils.isEmpty(messages)) {
            return;
        }
        OpenAIChatMessageRequest message = messages.get(messages.size() - 1);
        message.setContent(content + "\n\n" + message.getContent());
    }

    public void rightPad(String content) {
        if (CollectionUtils.isEmpty(messages)) {
            return;
        }
        OpenAIChatMessageRequest message = messages.get(messages.size() - 1);
        message.setContent(message.getContent() + "\n\n" + content);
    }

    /**
     * @description 获取请求体
     * <p> <功能详细描述> </p>
     *
     * @author 陈晨
     * @date 2023/4/12 15:41
     */
    public static String getRequestBody(OpenAIChatRequest chatRequest) {
        String requestJson = JSONObject.toJSONString(chatRequest);
        log.info("[GPT请求] chatRequest={}, 请求内容", requestJson);
        return requestJson;
    }

}


